﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ServiceProcess;
using System.Text;

namespace Universe.Farm.Builtin.WinServicesListener
{
    class WinServicesHealth : IServiceHealthListener
    {
        private List<string> _serviceNames;
        
        public WinServicesHealth() : this("Server", "W3SVC")
        {
        }

        public WinServicesHealth(params string[] serviceNames)
        {
            _serviceNames = new List<string>(serviceNames);
        }

        public Type DescryptionType
        {
            get { return typeof (WinServicesInfo); }
        }

        public object Ping
        {
            get { return GetInfo(); }
        }

        public string DefaultID
        {
            get { return "Dummy Service Listener"; }
        }

        public TimeSpan DefaultPingInterval
        {
            get { return TimeSpan.FromSeconds(20); }
        }

        private WinServicesInfo GetInfo()
        {
            WinServicesInfo ret = new WinServicesInfo();
            ret.Services = new List<WinServicesInfo.ServiceInfo>();

            foreach (string name in _serviceNames)
            {
                WinServicesInfo.ServiceInfo info = new WinServicesInfo.ServiceInfo();
                info.ServiceName = name;
                try
                {
                    ServiceController controller = new ServiceController(name);
                    controller.Refresh();
                    info.Status = controller.Status;
                    info.Present = true;
                    ret.Services.Add(info);
                }
                catch (InvalidOperationException ex)
                {
                    Win32Exception iex = ex.InnerException as Win32Exception;
                    if (iex != null && iex.NativeErrorCode == 1060)
                    {
                        info.Present = false;
                        ret.Services.Add(info);
                    }
                }
            }

            return ret;
        }
    }
}